package com.tg.app.util;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;

public class WebSoftInputHelper {

    // For more information, see https://issuetracker.google.com/issues/36911528

    public static void assistActivity(@NonNull Activity activity) {
        new WebSoftInputHelper(activity);
    }

    private final View mContentParent;
    View mDecorView;
    private int keyboardHeightPrevious;

    private WebSoftInputHelper(@NonNull Activity activity) {
        mDecorView = activity.getWindow().getDecorView();
        mContentParent = mDecorView.findViewById(android.R.id.content);
        mDecorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                possiblyResizeChildOfContent();
            }
        });
    }

    private void possiblyResizeChildOfContent() {
        Rect r = new Rect();
        mContentParent.getWindowVisibleDisplayFrame(r);
        int keyboardHeight = mContentParent.getBottom() - r.bottom;
        if (keyboardHeight != keyboardHeightPrevious) {
            mContentParent.setPadding(mContentParent.getPaddingLeft(),
                    mContentParent.getPaddingTop(),
                    mContentParent.getPaddingRight(),
                    keyboardHeight);
            keyboardHeightPrevious = keyboardHeight;
        }
    }

}
